
// //请求截图
// if(!requestScreenCapture(true)){
//     toast("请求截图失败");
//     exit();
// }else{
//     log('截图权限')
// }
// $images.requestScreenCapture();

// var imgs = {}
// imgs.find = function(name){

//     try {
//         //截图
//         // 初始化ColorMapping
//         let ColorMapping = $colors.mapping;
//         // 创建ColorMapping实例
//         let cm = new ColorMapping();
//         // 截屏
//         let img = $images.captureScreen();
//         // 初始化颜色映射
//         cm.reset(img);
//         let cd = d[name]

//         let newoption = cd[2]



//         width = newoption["region"][2] - newoption["region"][0]
//         height = newoption["region"][3] - newoption["region"][1]

//         log(cd[2], newoption, width, height)

//         var p = cm.findMultiColors(cd[0],cd[1], { region:[newoption["region"][0],newoption["region"][1],width,height],threshold: 20 } )
//         cm.recycle();

//         if ( p ){///////////////
//             log('找到=> '+ name)
//             if ( cd[3] ){
//                 if (!cd[4]) { cd[4] = 1 }
//                 f.click(p.x,p.y,cd[4],name )
//             }
//             return p
//         }
//     } catch (error) {
//         console.log(error)
//     }

// }


//新版基础函数
var f = {
    init:function() {
        log("程序初始化")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (x,y,x1,y1,times){
        swipe(x,y,x1,y1,times);
        sleep(1000);
    },
    getTextById: function (idstr) {
        try {
            return id(idstr).findOne(200).text()
        } catch (e) {
            log(e)
        }
    }
}
f.init()


//批查打印app参数
function printAll( ways ) {
    if (!ways){
        ways = 'className'
    }
    if (ways = 'className'){
        var all_Info = classNameMatches(/.*/).find();
    }else
    if (ways == 'text'){
        var all_Info = textMatches(/.*/).find();
    }else
    if (ways == 'id'){
        var all_Info = idMatches(/.*/).find();
    }else{
        eval( 'var all_Info = ' + ways + '.find();'  )
    }
    
    if ( all_Info ){
        for (var i = 0;i<all_Info.length;i++){
            var d = all_Info[i];
            log(i,d.id(),d.text(),"desc:"+d.desc(),'"className":"'+d.className()+'"',
            "clickable->"+d.clickable(),'selected->'+selected(),"depth->"+d.depth(),
            d.bounds().centerX(),d.bounds().centerY())
        }
    }else{
        log('没有找到任何相关的节点')
    }
}

// printAll()



function sbzs() {
    var phones = [
    //   'samsung',
    //   'Xiaomi',
    //   'Sony',
      'OPPO',
    //   'XIAOMI',
    //   'vivo',
    //   'HUAWEI',
    //   'HONOR'
    ]
  
    var i = 0
    let key = false
    while (i < 30) {
      f.active(appinfo.sbzs, 5)
      f.ms({ "text": "一键新机" }, true, 2)
  
      if (f.ms({ "text": "当前设备" }, false, 2)) {
  
        if (key) {
          sleep(1000)
          return true
        }
  
        var ids = [
          'phone_vendor',
          'phone_brand',
          'phone_model',
          'phone_serial_number',
          'android_id',
          'imsi',
          'wifi_mac',
          'op_name',
          'btaddr',
          'displayid',
          'baseband',
        ]
  
        appinfo.device = {}
        for (let Ii = 0; Ii < ids.length; Ii++) {
          appinfo.device[ids[Ii]] = f.getTextById(ids[Ii])
        }
  
        f.ms({ "text": "修改设备信息" }, true, 2)
      }
      else if (f.ms({ "text": "设备属性设置" }, false, 2)) {
        f.ms({ "text": "指定机型" }, true, 2)
        f.ms({ "id": "brand" }, true, 2)
  
        f.ms({ "text": "OPPO", 'id': 'brand' }, true)
        f.ms({ "text": "下一步" }, true, 2)
  
      } else if (f.ms({ "text": "立即清理" }, false, 2)) {
        key = true
        f.ms({ "text": appinfo.appname }, true, 2)
        f.ms({ "text": "立即清理" }, true, 2)
      }
  
      f.ms({ "text": "OPPO", 'id': 'brand' }, true)
      sleep(1000)

      i++
    }
}




function back_info(){
    let appids = "com.keramidas.TitaniumBackup"
    let appnames = "钛备份"

    var i = 0
    let key = false
    while (i < 40) {
        log("准备备份")
        f.active(appids, 5)
        f.ms({ "textMatches": "不要再显示此内容.*" }, true, 2)
        f.ms({ "textMatches": "确定" }, true, 2)
        if (f.ms({ "text": "正在备份" })) {

        }else{
            if ( f.ms({ "text": "备份/还原" }, false, 2) ){
                if ( key ){
                    return true
                }

                f.ms({ "text": "备份/还原" }, true, 2)
                f.ms({ "textMatches": "锦江荟.*" }, true, 2)
                if ( f.ms({ "text": "备份！" }, true, 2)){
                    key = true
                }
            }
        }
        sleep(1000)
        i++
    }

}


//上传idfa
function Idfa(other){
    let postArr = {};
    postArr['service'] = 'Idfa.idfa';
    postArr['name'] = appinfo.name;
    postArr['idfa'] = appinfo.device.android_id;
    postArr['account'] = appinfo.device.wifi_mac;
    postArr['appid'] = appinfo.device.phone_serial_number;
    postArr['password'] = appinfo.device.baseband;
    postArr['phoneimei'] = appinfo.device.imsi;
    postArr['phoneos'] = appinfo.device.btaddr;
    postArr['decice'] = JSON.stringify(appinfo.device);
    postArr['other'] = other ? other : "成功";
    let data = f.post("http://wenfree.cn/api/Public/idfa/",postArr);
    var res = JSON.parse(data);
    if(res){
        toastLog("上传成功")
        return res.data.id
    }
}


function checkIp(){
    url = "http://wenfree.cn/api/Public/idfa/?service=Ip.Checkip&ip="
    r = f.post(url,{})
    log(r)
    if (r){
        r = JSON.parse(r)
        if ( r.data.state == "ok"){
            toastLog(r.data.ip + "可以使用")
            return true
        }
    }
}


/* eslint-disable */
var Base64 = {
    // private property
    _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
    // public method for encoding
    encode: function (input) {
        var output = ''
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4
        var i = 0
        input = Base64._utf8_encode(input)
        while (i < input.length) {
        chr1 = input.charCodeAt(i++)
        chr2 = input.charCodeAt(i++)
        chr3 = input.charCodeAt(i++)
        enc1 = chr1 >> 2
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
        enc4 = chr3 & 63
        if (isNaN(chr2)) {
            enc3 = enc4 = 64
        } else if (isNaN(chr3)) {
            enc4 = 64
        }
        output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)
        }
        return output
    },
    // public method for decoding
    decode: function (input) {
        var output = ''
        var chr1, chr2, chr3
        var enc1, enc2, enc3, enc4
        var i = 0
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '')
        while (i < input.length) {
        enc1 = this._keyStr.indexOf(input.charAt(i++))
        enc2 = this._keyStr.indexOf(input.charAt(i++))
        enc3 = this._keyStr.indexOf(input.charAt(i++))
        enc4 = this._keyStr.indexOf(input.charAt(i++))
        chr1 = (enc1 << 2) | (enc2 >> 4)
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)
        chr3 = ((enc3 & 3) << 6) | enc4
        output = output + String.fromCharCode(chr1)
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2)
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3)
        }
        }
        output = Base64._utf8_decode(output)
        return output
    },
    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, '\n')
        var utftext = ''
        for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n)
        if (c < 128) {
            utftext += String.fromCharCode(c)
        } else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192)
            utftext += String.fromCharCode((c & 63) | 128)
        } else {
            utftext += String.fromCharCode((c >> 12) | 224)
            utftext += String.fromCharCode(((c >> 6) & 63) | 128)
            utftext += String.fromCharCode((c & 63) | 128)
        }
        }
        return utftext
    },
    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = ''
        var i = 0
        var c = c1 = c2 = 0
        while (i < utftext.length) {
        c = utftext.charCodeAt(i)
        if (c < 128) {
            string += String.fromCharCode(c)
            i++
        } else if ((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i + 1)
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))
            i += 2
        } else {
            c2 = utftext.charCodeAt(i + 1)
            c3 = utftext.charCodeAt(i + 2)
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
            i += 3
        }
        }
        return string
    }
}



function upUpyun(local_path,file_name){
    var date = new Date()
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var Operator = 'ouwen000'
    var opts = {
        'save-key': '/zip/'+year+'/'+month+'/'+ day +'/'+file_name,
        bucket: 'wey-suv',
        expiration: Math.round(new Date().getTime() / 1000) + 3600,
    }
    // log(JSON.stringify(opts))
    var policy = Base64.encode(JSON.stringify(opts))
    var data = ['POST', '/' + opts.bucket, policy].join('&')
    // log("data", opts, data)
    // 进行 URL 编码
    var encodedString = data.replace(/&/g, "%26").replace(/\//g, "%2F").replace(/:/g, "%3A").replace(/ /g, "%20").replace(/=/g, "%3D").replace(/,/g, "%2C");
    // log("encodedString", encodedString)
    var url = "https://ad.wenfree.cn/?data=" + encodedString
    // log("url", url)
    var r = http.get(url)
    var signature = JSON.parse(r.body.string()).signature;
    // var signature = "p/Xq1SsWJlc+BDD+e67gPthkJ0E=";
    // log("signature", signature)
    var headers = {
        'Content-Type': 'multipart/form-data;',
    }
    // log("headers", headers, policy)
    var url = 'https://v0.api.upyun.com/'+ opts.bucket
    var res = http.postMultipart(url,
        {
            authorization: 'UPYUN ' + Operator + ':' + signature,
            policy: policy,
            file: open(local_path),
        },
        {
            headers: headers,
        }
    )
    // log("res", res);
    var res_ = JSON.parse(res.body.string())
    var urls = "https://img.wenfree.cn" + res_.url
    log("urls", urls);
    return urls;
}

// upUpyun('1.zip')
function file_name_list(){

    var dir = "/sdcard/TitaniumBackup/";
    var jsFiles = files.listDir(dir, function(name){
        return (name.endsWith(".tar.gz") || name.endsWith(".properties")) && files.isFile(files.join(dir, name));
    });
    return jsFiles;
}


// 正式开始编代码
var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);
var appinfo = {}
appinfo.name = "锦江荟";
appinfo.bid = "com.kyscgenuiphone";
appinfo.link = "https://app.dkmobile-genesis.one/";
appinfo.llq = "com.android.chrome";
appinfo.gzbid = "com.deruhai.guangzi";
appinfo.sbdsbid = "com.longene.setcardproperty";
appinfo.sbzs = "com.blue.backup";
info ={};


function getTask(){
    let url = "http://wenfree.cn/api/Public/tjj/?service=Tjj.gettask"
    let postData = {
        phonename: "青蛙",
        imei: "qingwa"
    }
    r = f.post(url,postData)
    // log(r)
    if (r){
        r = JSON.parse(r)
        if ( r.data == "新增手机" || r.data == "暂无任务"){
            toastLog(r.data)
            return false
        }else{
            return r.data
        }
    }
}

function back_pass(task_id,success){
	let url = 'http://wenfree.cn/api/Public/tjj/?service=Tjj.backpass'
	let postArr = {}
	postArr.task_id = task_id
	postArr.success = success
	log( f.post(url,postArr) )
}

function update_info(id, data){
    let url = "https://idfaapi.wenfree.cn/?s=App.Index.Update"
    let postData = {
        id: id,
        arr: JSON.stringify(data),
        table: "tbl_idfa888_idfa"
    }
    f.post(url,postData)
}


function main(){
    
    let i = 60
    while ( i > 0 ){
        f.active(appinfo.bid, 5)

        f.ms({"id":"ivAllAgree"}, true, 2)

        f.ms({"textMatches":"今日不再提示"}, true, 2)
        f.ms({"text":"同意并继续使用"}, true, 2)
        f.ms({"text":"跳过"}, true, 3)
        
        f.click(590+5,190+5,1,'x')

        f.ms({"text":"会员"}, true, 2)
        f.ms({"text":"确定"}, true, 2)

        if (f.ms({"text": "登录/注册"} )) {
            return true
        }

        i--
        sleep(1000)
    }
    return true
}


function all(){

    if (true || hmip() ){

        sleep(1000*2)

        if ( sbzs() ){
            if ( true || getsbds() ){
        
                if ( main() ){
                    back_info()
                    var id = Idfa("全息备份")
                    if (id){
                       var file_list = file_name_list()
                       if(file_list){
                           for (let i=0;i<file_list.length;i++){
                                var file_name = file_list[i]
                                var filej = new java.io.File('/sdcard/TitaniumBackup/'+file_name);
                                var fileSizeInBytes = filej.length();
                                if( fileSizeInBytes < 5242880 ){
                                    var url = upUpyun('/sdcard/TitaniumBackup/'+file_name,file_name)
                                    if (url){
                                        if (url.split('.').pop() === 'gz') {
                                            update_info(id, {"zip_url":url})
                                        }else{
                                            update_info(id, {"txt_url":url})
                                        }
                                    }
                                }
                            }
                        }
                        return true
                    }
                }
                f.ms({"textMatches":".*关闭.*"},true,2)
            }
            f.ms({"textMatches":".*关闭.*"},true,2)
        }
    }
    f.ms({"textMatches":".*关闭.*"},true,2)
}

console.show();


// var file_show = files.listDir("/sdcard/TitaniumBackup/");

// log(  file_show  )

// var id = 12216903
// if (id){
//     var file_list = file_name_list()
//     if(file_list){
//         log(file_list)
//         for (let i=0;i<file_list.length;i++){
//              var file_name = file_list[i]
//              var url = upUpyun('/sdcard/TitaniumBackup/'+file_name,file_name)
//              if (url){
//                  if (url.split('.').pop() === 'gz') {
//                      update_info(id, {"zip_url":url})
//                  }else{
//                      update_info(id, {"txt_url":url})
//                  }
//              }
//          }
//      }
//  }

// var file = new java.io.File("/sdcard/1.txt");
// var fileSizeInBytes = file.length();
// var fileSizeInKB = fileSizeInBytes / 1024;
// var fileSizeInMB = fileSizeInKB / 1024;

// console.log("File Size: " + fileSizeInBytes + " bytes");
// console.log("File Size: " + fileSizeInKB + " KB");
// console.log("File Size: " + fileSizeInMB + " MB");



var file_list = file_name_list()
if(file_list){
    log(file_list)
    for (let i=0;i<file_list.length;i++){
        var file_name = file_list[i]
        var removelog = files.remove('/sdcard/TitaniumBackup/'+file_name)
        log(removelog)
    }
}

//  exit()

while ( true ){

    var ipvpn = 0
    try {

        var TaskData = getTask()
        if ( TaskData ){
            for (let i=0;i<TaskData.length;i++){
                var TaskInfo = TaskData[i]

                log(TaskInfo.work)
                // log(TaskInfo)
                appinfo.bid = TaskInfo.appbid
                appinfo.name = TaskInfo.work
                appinfo.appname = TaskInfo.keyword

                if ( all() ){
                    back_pass(TaskInfo.task_id, "ok")
                }

                sleep(1000)
            }
        }else{

            sleep(1000*20)
            // hmip_close()

        }

    } catch (error) {
        log(error)
        // hmip_close()
        sleep(5000)
    }

}





